from typing import List
from src.db import dbm, dbs
from typing import Annotated
from pydantic import BaseModel
from sqlalchemy.orm import scoped_session
from pydantic import Field, AfterValidator
from src.core.variables.info import FUNCTIONS, FUNCTIONS_BEHAVIOR


# 自定义类型验证器
class _Validate:
    def sse_id_s(v: list) -> list:
        """验证SSE连接ID列表"""
        # if type(v) is not list:
        #     raise TypeError("sse_id_s必须是一个列表")
        # for i in v:
        #     if Cache.SSE_CACHE.get(f"{i}") is not None:
        #         continue
        #     raise ValueError(f"SSE连接不存在: {i}")
        return v

    def on_function(v: str) -> str:
        """验证函数名"""
        if v not in FUNCTIONS:
            raise ValueError(f"功能不存在: {v}")
        return v

    def on_behavior(v: str) -> str:
        """验证行为"""
        if v not in FUNCTIONS_BEHAVIOR:
            raise ValueError(f"行为不存在: {v}")
        return v

    def on_cert(v: dict) -> dict:
        """验证证书格式"""
        if "key" in v and "data" in v:
            return v
        else:
            raise ValueError("证书格式错误")

    def on_node_id(v: str) -> str:
        """验证节点ID"""
        with dbm.get("sys_default") as db_session:
            db_session: scoped_session
            if (
                db_session.query(dbs.sys_default.Node)
                .filter(dbs.sys_default.Node.node_id == v)
                .count()
                > 0
            ):
                return v
            else:
                raise ValueError(f"节点不存在: {v}")


class close_sse_schema(BaseModel):
    """关闭SSE连接"""

    sse_id_s: Annotated[List[str], AfterValidator(_Validate.sse_id_s)] = Field(
        ..., description="指定要关闭的sse_id, 格式是一个列表"
    )


class nodes_bind_schema(BaseModel):
    """多节点注册"""

    cert: Annotated[str, AfterValidator(_Validate.on_cert)] = Field(
        ..., min_length=1, description="绑定信息证书"
    )


class function_control_schema(BaseModel):
    """函数控制"""

    name: Annotated[str, AfterValidator(_Validate.on_function)] = Field(
        ..., min_length=1, description="功能"
    )
    behavior: Annotated[str, AfterValidator(_Validate.on_behavior)] = Field(
        ..., min_length=1, description="行为"
    )


class unbind_node_schema(BaseModel):
    """取消节点绑定"""

    node_id: Annotated[str, AfterValidator(_Validate.on_node_id)] = Field(
        ..., min_length=1, description="节点ID"
    )